//
//  RestaurantDetailViewController.swift
//  FeastBooking
//
//  Created by Imon on 2017/7/8.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit
import RxSwift
import Kingfisher

class RestaurantDetailViewController: UIViewController {

    let restaurantVM = RestaurantViewModel.share
    
    let authManager = AuthManager.share
    
    var favouriteVM: FavouriteViewModel?
    
    //let userAuthVM = UserAuthViewModel.shared
    
    let disposeBag = DisposeBag()
    
    var restaurant: RestaurantDetailResponse?
    
    var scrollView: UIScrollView?
    
    var imageScrollView: UIScrollView?
    
    let picture_ph = UIImage(named: "ph_long")!
    
    let promotionIcon: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "promotion")
        view.contentMode = .scaleAspectFill
        return view
    }()
    
    @IBOutlet weak var button: UIButton!
    
    @IBOutlet weak var pageControl: UIPageControl!
    
    var navigatingView: UIView?
    var backButton: UIButton?
    var shareButton: UIButton?
    
    var numOfComments: Int = 0
    
    let nameLabel: UILabel = {
        let label = UILabel()
        label.font = moreFont(size: 19)
        label.numberOfLines = 0
        label.textColor = UIColor.black
        label.text = LanguageHelper.getString(key: "NO_RESULT")
        return label
    }()
    
    let grade: GradeView = {
        let view = GradeView()
        view.initValue(grade: 0.0)
        return view
    }()
    
    let discountMessage: UILabel = {
        let label = UILabel()
        label.font = AppFont(size: 12)
        label.textColor = UIColor.lightGray
        label.numberOfLines = 0
        return label
    }()
    
    let saperator: UIView = {
        let view = UIView()
        return view
    }()
    
    let descriptionLabel: UILabel = {
        let label = UILabel()
        label.font = AppFont(size: 12)
        label.numberOfLines = 0
        label.textColor = UIColor.gray
        return label
    }()
    
    var discounts: [RestaurantDiscount] = []
    
    let addressInfo: UIView = UIView()
    
    let telInfo: UIView = UIView()
    
    let commentInfo: UIView = UIView()
    
    let like: TitleButton = {
        let button = TitleButton()
        button.setImage(UIImage(named: "like_unselected"), for: .normal)
        button.setImage(UIImage(named: "like_selected"), for: .selected)
        button.setTitle(LanguageHelper.getString(key: "LIKE"), for: .normal)
        button.titleLabel?.textColor = UIColor.lightGray
        button.titleLabel?.font = AppFont(size: 12)
        return button
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        getDiscount()
        setLayout()
//        button.layer.cornerRadius = 3
//        button.layer.masksToBounds = true

    }
    
    func setLayout() {
        scrollView = UIScrollView()
        scrollView?.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height - 50)
        scrollView?.showsVerticalScrollIndicator = false
        scrollView?.showsHorizontalScrollIndicator = false
        scrollView?.isScrollEnabled = true
        scrollView?.autoresizingMask = UIViewAutoresizing.flexibleHeight
        scrollView?.backgroundColor = lightSaperatorColor
        scrollView?.delegate = self
        
        imageScrollView = UIScrollView()
        let width = self.view.frame.width
        imageScrollView?.frame = CGRect(x: 0, y: 0, width: width, height: width * 2 / 3)
        imageScrollView?.isPagingEnabled = true
        imageScrollView?.isScrollEnabled = true
        imageScrollView?.showsVerticalScrollIndicator = false
        imageScrollView?.showsHorizontalScrollIndicator = false
        imageScrollView?.scrollsToTop = false
        imageScrollView?.delegate = self
        var contentCount = 1
        if let urls = restaurant?.pictureUrls {
            if urls.count > 0 {
                contentCount = urls.count
                for i in 0...contentCount - 1 {
                    let imageView = UIImageView()
                    imageView.contentMode = .scaleAspectFill
                    imageView.layer.masksToBounds = true
                    imageView.frame = CGRect(x: CGFloat(i) * (imageScrollView?.frame.size.width)!, y: 0, width: (imageScrollView?.frame.size.width)!, height: (imageScrollView?.frame.size.height)!)
                    let url = URL(string: urls[i])
                    imageView.kf.setImage(with: url, placeholder: UIImage(named: "loading"))
                    imageScrollView?.addSubview(imageView)
                }
            } else {
                setDefaultImage()
            }
        } else {
            setDefaultImage()
        }
        
        imageScrollView?.contentSize = CGSize(width: (imageScrollView?.frame.width)! * CGFloat(contentCount), height: (imageScrollView?.frame.height)!)
        pageControl.numberOfPages = contentCount
        pageControl.alpha = 0
        pageControl.currentPage = 0
        scrollView?.addSubview(imageScrollView!)
        
        let infoLeading: CGFloat = 15
        
        nameLabel.text = restaurant?.name
        let textMaxSize = CGSize(width: self.view.bounds.width - 20, height: self.view.frame.height)
        let nameSize = TextSize.textSize(text: nameLabel.text!, font: nameLabel.font, maxSize: textMaxSize)
        nameLabel.frame = CGRect(x: infoLeading, y: 15, width: nameSize.width, height: nameSize.height)
        if let rating = restaurant?.rating {
            grade.initValue(grade: CGFloat(rating))
        }
        grade.frame = CGRect(x: infoLeading, y: nameLabel.frame.origin.y + nameLabel.frame.height + 8, width: 150, height: 20)
        discountMessage.text = "\(LanguageHelper.getString(key: "RESENT_DISCOUNT"))："
        for discount in discounts {
            if let date = discount.date, let dis = discount.discount {
                discountMessage.text! += "\n\(date): \(dis)"
            }
        }
        let discountSize = TextSize.textSize(text: discountMessage.text!, font: discountMessage.font, maxSize: textMaxSize)
        discountMessage.frame = CGRect(x: infoLeading + 15, y: grade.frame.origin.y + grade.frame.height + 8, width: discountSize.width, height: discountSize.height)
        
        promotionIcon.frame = CGRect(x: infoLeading, y: discountMessage.frame.origin.y, width: 12, height: 12)
        saperator.backgroundColor = UIColor.lightGray
        saperator.frame = CGRect(x: infoLeading, y: discountMessage.frame.origin.y + discountMessage.frame.height + 5, width: self.view.bounds.width - 30, height: 0.5)
        descriptionLabel.text = restaurant?.rest_description
        let descriptionSize = TextSize.textSize(text: descriptionLabel.text!, font: descriptionLabel.font, maxSize: textMaxSize)
        descriptionLabel.frame = CGRect(x: infoLeading, y: saperator.frame.origin.y + saperator.frame.height + 8, width: descriptionSize.width, height: descriptionSize.height + 15)
        
        let descriptionArea = UIView()
        descriptionArea.backgroundColor = UIColor.white
        descriptionArea.frame = CGRect(x: 0, y: (imageScrollView?.frame.height)!, width: self.view.bounds.width, height: descriptionLabel.frame.origin.y + descriptionLabel.frame.height + 5)
        
        descriptionArea.addSubview(nameLabel)
        descriptionArea.addSubview(grade)
        descriptionArea.addSubview(discountMessage)
        descriptionArea.addSubview(promotionIcon)
        descriptionArea.addSubview(saperator)
        descriptionArea.addSubview(descriptionLabel)
        
        scrollView?.addSubview(descriptionArea)
        
        var yAfterBH = descriptionArea.frame.origin.y + descriptionArea.frame.height + 10
        
        setMoreInfoArea()
        
        let moreInfoArea = UIView()
        moreInfoArea.backgroundColor = UIColor.white
        moreInfoArea.frame = CGRect(x: 0, y: yAfterBH, width: self.view.bounds.width, height: commentInfo.frame.origin.y + commentInfo.frame.height)
        
        moreInfoArea.addSubview(addressInfo)
        moreInfoArea.addSubview(telInfo)
        moreInfoArea.addSubview(commentInfo)
        scrollView?.addSubview(moreInfoArea)
        
        
        yAfterBH = moreInfoArea.frame.origin.y + moreInfoArea.frame.height + 10
        
        if let banquetHalls = restaurant?.banquetHalls {
            if banquetHalls.count > 0 {
                yAfterBH = setBanquetHall(originHeight: yAfterBH, banquetHalls: banquetHalls)
            }
        }
        
        var yAfterFM = yAfterBH + 10
        
        if let feasts = restaurant?.feasts {
            //设置宴席菜单
            if feasts.count > 0 {
                yAfterFM = setFeastMenu(originHeight: yAfterFM, feasts: feasts)
            }
        }
        
        let h1 = yAfterFM
        let h2 = (self.scrollView?.frame.height)! + 0.5
        let contentHeight: CGFloat = h1 > h2 ? h1 : h2
        scrollView?.contentSize = CGSize(width: self.view.bounds.width, height: contentHeight)
        self.view.addSubview(scrollView!)
        
        setNavigatingView()
        
        backButton = UIButton()
        backButton?.frame = CGRect(x: 12, y: 30, width: 28, height: 28)
        backButton?.setImage(UIImage(named: "back"), for: .normal)
        backButton?.setImage(UIImage(named: "back_black"), for: .selected)
        backButton?.addTarget(self, action: #selector(backForButton(_:)), for: .touchUpInside)
        self.view.insertSubview(backButton!, aboveSubview: navigatingView!)
        
        shareButton = UIButton()
        shareButton?.frame = CGRect(x: self.view.bounds.width - 32 - 12, y: 32, width: 32, height: 32)
        shareButton?.setImage(UIImage(named: "share"), for: .normal)
        shareButton?.setImage(UIImage(named: "share_black"), for: .selected)
        shareButton?.addTarget(self, action: #selector(share(_:)), for: .touchUpInside)
        self.view.insertSubview(shareButton!, aboveSubview: navigatingView!)
        
        like.frame = CGRect(x: (button.frame.origin.x - 55) / 2, y: self.view.frame.height - 48, width: 40, height: 40)
        like.addTarget(self, action: #selector(likeRestaurant(sender:)), for: .touchUpInside)
        self.view.addSubview(like)
        // Do any additional setup after loading the view.
        
        setLikeBtnStatus()
    }
    
    func getDiscount() {
        let now = Date()
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy.MM.dd"        
        restaurantVM.getRestaurantDiscount(hotelId: (restaurant?.id)!, since: formatter.string(from: now)).subscribe(onNext: { [unowned self] discounts in
            self.discounts = discounts
            self.setLayout()
//            for dis in discounts {
//                print("折扣返回！\(dis.date) \(dis.discount)")
//            }
        })
        .addDisposableTo(disposeBag)
    }
    
    func showCommentPage(_ sender: UITapGestureRecognizer) {
        let commentPage = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "RestaurantCommentsViewController") as! RestaurantCommentsViewController
        commentPage.restaurant = restaurant
//        detailPage.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(commentPage, animated: true)
    }
    
    func setLikeBtnStatus() {
        initVM()
        if let vm = favouriteVM {
            vm.checkFavourite(id: (restaurant?.id)!).subscribe(onNext: { [unowned self] restaurant in
                if restaurant.id != nil {
                    self.like.isSelected = true
                }
            })
            .addDisposableTo(disposeBag)
        }
    }
    
    func initVM() {
        let authManager = AuthManager.share
        if authManager.hasLogined() {
            if let token = authManager.getToken() as? String {
                favouriteVM = FavouriteViewModel(token: token)
            }
        }
    }
    
    func setDefaultImage() {
        //沒有附带照片
        let imageView = UIImageView(image: UIImage(named: "ph_long"))
        imageView.contentMode = .scaleAspectFill
        imageView.layer.masksToBounds = true
        imageView.frame = CGRect(x: 0, y: 0, width: (imageScrollView?.frame.size.width)!, height: (imageScrollView?.frame.size.height)!)
        imageScrollView?.addSubview(imageView)
    }
    
    func likeRestaurant(sender: UIButton) {
        if authManager.hasLogined() {
            if like.isSelected {
                favouriteVM?.deleteFavourite(id: (restaurant?.id)!).subscribe(onNext: { [unowned self] string in
                    if string == "true" {
                        self.like.isSelected = false
                    }
                })
                .addDisposableTo(disposeBag)
            } else {
                favouriteVM?.setFavourite(id: (restaurant?.id)!).subscribe(onNext: { [unowned self] string in
                    if string == "true" {
                        self.like.isSelected = true
                    }
                })
                .addDisposableTo(disposeBag)
            }
        } else {
            showLoginPage()
        }
    }
    
    func setMoreInfoArea() {
        let leading: CGFloat = 15
        let imageSize: CGFloat = 20
        let top: CGFloat = 10
        
        let textMaxSize = CGSize(width: self.view.bounds.width - 2 * (leading * 2 + imageSize), height: self.view.bounds.height)
        
        let addressLabel = UILabel()
        addressLabel.numberOfLines = 0
        addressLabel.font = AppFont(size: 13)
        addressLabel.textColor = UIColor.lightGray
        addressLabel.text = "\(restaurant?.address?.city ?? "") \(restaurant?.address?.district ?? "") \(restaurant?.address?.street ?? "")"
        let addrImageView = UIImageView(image: UIImage(named: "location"))
        addrImageView.contentMode = .scaleAspectFit
        let addrSaperator = UIView()
        addrSaperator.backgroundColor = saperatorColor
        let addrSize = TextSize.textSize(text: addressLabel.text!, font: addressLabel.font, maxSize: textMaxSize)
        var addrHeight = addrSize.height + 2 * top
        addrHeight = addrHeight > menuHeight ? addrHeight : menuHeight
        
        addressInfo.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: addrHeight)
        addressLabel.frame = CGRect(x: leading * 2 + imageSize, y: (addrHeight - addrSize.height) / 2, width: addrSize.width, height: addrSize.height)
        addrImageView.frame = CGRect(x: leading, y: (addrHeight - imageSize) / 2, width: imageSize, height: imageSize)
        addrSaperator.frame = CGRect(x: leading, y: addrHeight - 0.5, width: self.view.bounds.width, height: 0.5)
        addressInfo.addSubview(addressLabel)
        addressInfo.addSubview(addrImageView)
        addressInfo.addSubview(addrSaperator)
        
        let telLabel = UILabel()
        telLabel.numberOfLines = 0
        telLabel.font = AppFont(size: 13)
        telLabel.textColor = UIColor.lightGray
        telLabel.text = "\(restaurant?.telephone ?? "")"
        let telImageView = UIImageView(image: UIImage(named: "tel"))
        telImageView.contentMode = .scaleAspectFit
        let telSaperator = UIView()
        telSaperator.backgroundColor = saperatorColor
        let telSize = TextSize.textSize(text: telLabel.text!, font: telLabel.font, maxSize: textMaxSize)
        
        telInfo.frame = CGRect(x: 0, y: addressInfo.bounds.height, width: self.view.bounds.width, height: telSize.height + 20)
        telLabel.frame = CGRect(x: leading * 2 + imageSize, y: (telInfo.frame.height - telSize.height) / 2, width: telSize.width, height: telSize.height)
        telImageView.frame = CGRect(x: leading, y: (menuHeight - imageSize) / 2, width: imageSize, height: imageSize)
        telSaperator.frame = CGRect(x: leading, y: telInfo.frame.height - 0.5, width: self.view.bounds.width, height: 0.5)
        telInfo.addSubview(telLabel)
        telInfo.addSubview(telImageView)
        telInfo.addSubview(telSaperator)
        
        numOfComments = restaurant?.numOfReviews != nil ? (restaurant?.numOfReviews)! : 0
        let commLabel = UILabel()
        commLabel.font = AppFont(size: 13)
        commLabel.textColor = UIColor.lightGray
        commLabel.text = "\(LanguageHelper.getString(key: "REVIEW"))（\(numOfComments)）"
        let commImageView = UIImageView(image: UIImage(named: "comment"))
        commImageView.contentMode = .scaleAspectFit
        let commSaperator = UIView()
        commSaperator.backgroundColor = saperatorColor
        let commSize = TextSize.textSize(text: commLabel.text!, font: commLabel.font, maxSize: textMaxSize)
        
        commentInfo.frame = CGRect(x: 0, y: addressInfo.bounds.height + telInfo.bounds.height, width: self.view.bounds.width, height: menuHeight)
        commLabel.frame = CGRect(x: leading * 2 + imageSize, y: (menuHeight - commSize.height) / 2, width: commSize.width, height: commSize.height)
        commImageView.frame = CGRect(x: leading, y: (menuHeight - imageSize) / 2, width: imageSize, height: imageSize)
        commSaperator.frame = CGRect(x: leading, y: menuHeight - 0.5, width: self.view.bounds.width, height: 0.5)
        commentInfo.addSubview(commLabel)
        commentInfo.addSubview(commImageView)
        commentInfo.addSubview(commSaperator)
        let comTapGR = UITapGestureRecognizer()
        comTapGR.addTarget(self, action: #selector(showCommentPage(_:)))
        commentInfo.addGestureRecognizer(comTapGR)
    }
    
    func setNavigatingView() {
        navigatingView = UIView()
        navigatingView?.backgroundColor = UIColor.white
        navigatingView?.alpha = 0
        navigatingView?.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 68)
        self.view.insertSubview(navigatingView!, aboveSubview: scrollView!)
    }
    
    func setBanquetHall(originHeight: CGFloat, banquetHalls: [RestaurantBanquetHall]) -> CGFloat {
        let bhWidth = UIScreen.main.bounds.width - 20
        let bhHeight = bhWidth / 2.8
        let gap: CGFloat = 15
        let count: CGFloat = CGFloat(banquetHalls.count)
        let bhBoard = BanquetHallBoard()
        bhBoard.frame = CGRect(x: 0, y: originHeight, width: self.view.bounds.width, height: 50 + bhHeight * count + gap * (count - 1) + 10)
        
        for i in 0...banquetHalls.count - 1 {
            let bhView = BanquetHallView()
            bhView.delegate = self
            bhView.initValue(banquetHall: banquetHalls[i])
            bhView.frame = CGRect(x: 10, y: 50 + (bhHeight + gap) * CGFloat(i), width: bhWidth, height: bhHeight)
            bhView.layoutSubviews()
            bhBoard.addSubview(bhView)
        }
        
        bhBoard.layoutSubviews()
        scrollView?.addSubview(bhBoard)
        return bhBoard.frame.origin.y + bhBoard.frame.height
    }
    
    func setFeastMenu(originHeight: CGFloat, feasts: [RestaurantFeast]) -> CGFloat {
        let menuHeader = MenuHeader()
        menuHeader.frame = CGRect(x: 0, y: originHeight, width: self.view.bounds.width, height: menuHeight)        
        menuHeader.layoutSubviews()
        scrollView?.addSubview(menuHeader)
        
        var FMs: [FeastMenu] = []
        
        for i in 0...feasts.count - 1 {
            let fm = FeastMenu()
            fm.delegate = self
            fm.feast = feasts[i]
            if let name = feasts[i].name {
                fm.titleLabel.text = name
            } else {
                fm.titleLabel.text = LanguageHelper.getString(key: "NO_RESULT")
            }
            if let price = feasts[i].price {
                fm.priceLabel.text = "\(price)/\(LanguageHelper.getString(key: "TABLE"))"
            } else {
                fm.priceLabel.text = LanguageHelper.getString(key: "DISHES")
            }
            fm.frame = CGRect(x: 0, y: menuHeader.frame.origin.y + menuHeight * CGFloat(i + 1), width: self.view.bounds.width, height: menuHeight)
            fm.layoutSubviews()
            scrollView?.addSubview(fm)
            FMs.append(fm)
        }

        return FMs[FMs.count - 1].frame.origin.y + FMs[FMs.count - 1].frame.height
    }
    
    //分享
    func share(_ sender: UIButton) {
        
    }
    
    @IBAction func changePage(_ sender: UIPageControl) {
        var newFrame = imageScrollView?.frame
        newFrame?.origin.x = (newFrame?.size.width)! * CGFloat(pageControl.currentPage)
        imageScrollView?.scrollRectToVisible(newFrame!, animated: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    @IBAction func consult(_ sender: UIButton) {
        if authManager.hasLogined() {
            showBookingView()
        } else {
            showLoginPage()
        }
    }
        
    private func showBookingView() {
        let bookingView = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "BookingViewController") as! BookingViewController
        bookingView.restaurant = self.restaurant
        bookingView.isBH = false
        self.navigationController?.pushViewController(bookingView, animated: true)
    }
    
    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
//    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//
//    }
    

}

extension RestaurantDetailViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let index = round(scrollView.contentOffset.x / UIScreen.main.bounds.size.width);
        pageControl.currentPage = Int(index)
        let offsetY = scrollView.contentOffset.y
        if offsetY < 100 {
            navigatingView?.alpha = 0
        } else if offsetY < (imageScrollView?.frame.height)! {
            let a = (offsetY - 100) / ((imageScrollView?.frame.height)! - 100)
            navigatingView?.alpha = a
        } else {
            navigatingView?.alpha = 1
        }
        if offsetY >= ((imageScrollView?.frame.height)! - (backButton?.frame.origin.y)!) {
            backButton?.isSelected = true
            shareButton?.isSelected = true
        } else {
            backButton?.isSelected = false
            shareButton?.isSelected = false
        }
    }
}

extension RestaurantDetailViewController: FeastMenuDelegate {
    
    func showFeastDetail(feast: RestaurantFeast) {
        restaurantVM.getFeast(id: feast.id!).subscribe(onNext: { [unowned self] feastDetail in
            let detailView = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "FeastDetailViewController") as! FeastDetailViewController
            detailView.feast = feastDetail
            self.navigationController?.pushViewController(detailView, animated: true)
        })
        .addDisposableTo(disposeBag)
    }
}

extension RestaurantDetailViewController: BanquetHallViewDelegate {
    
    func showBanquetHall(banquetHall: RestaurantBanquetHall) {
        restaurantVM.getBanquetHall(id: banquetHall.id!).subscribe(onNext: { [unowned self] banquetHallDetail in
            let detailView = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "BanquetHallDetailViewController") as! BanquetHallDetailViewController
            detailView.banquetHall = banquetHallDetail
            detailView.restaurant = self.restaurant
            self.navigationController?.pushViewController(detailView, animated: true)
        })
        .addDisposableTo(disposeBag)
    }
}

